package com.aloaproject.ciquta;

/**
 * Generic criterion that retrieve a property and delegate the match to another class.
 * @author Daniele Demichelis
 */
public class GenericCriterion implements Criterion {

    private final Object referenceValue;
    private final String propertyPath;
    private Matcher matcher;

    GenericCriterion(Matcher matcher, final String propertyPath, final Object referenceValue) {
        
        if(matcher == null){
            throw new IllegalArgumentException("matcher cannot be null.");
        }
        
    	//.isEmpty() does not seems java 1.5        
        if(propertyPath == null || propertyPath.trim().length()==0){
            throw new IllegalArgumentException("propertyPath cannot be null.");
        }
        
        this.matcher = matcher;
        this.referenceValue = referenceValue;
        this.propertyPath = propertyPath;
    }

    public final boolean match(final Object object) {
        try {
            Object actualValue = org.apache.commons.beanutils.PropertyUtils.getProperty(object, propertyPath);
            return matcher.test(referenceValue, actualValue);
        } catch (NoSuchMethodException ex) {
            return false;
        } catch (Exception ex) {
            if(ex instanceof RuntimeException){
                throw (RuntimeException) ex;
            }else{
                throw new RuntimeException(ex);
            }
        }
    }

}
